/**
 * 文件类型tab
 *
 * 类型【一级分类、二级分类、三级分类】
 *
 */
import { useEffect, useRef, useState } from "react";
import {
  Button,
  Space,
  Table,
  Tag,
  Segmented,
  Modal,
  Select,
  Input,
  Form,
  Upload,
  message,
  Col,
  Row,
} from "antd";
import "./index.less";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  DownloadOutlined,
  UploadOutlined,
} from "@ant-design/icons";
import * as XLSX from "xlsx";
import { v4 } from "uuid";
import { thingsTypeList, getRandomNumberGreaterThan10000 } from "./utils";

// 表格数据
const testTableDataList = [
  {
    key: "1",
    name: "John Brown",
    age: 32,
    address: "New York No. 1 Lake Park",
    tags: ["nice", "developer"],
  },
  {
    key: "2",
    name: "Jim Green",
    age: 42,
    address: "London No. 1 Lake Park",
    tags: ["loser"],
  },
  {
    key: "3",
    name: "Joe Black",
    age: 32,
    address: "Sidney No. 1 Lake Park",
    tags: ["cool", "teacher"],
  },
];

const TabList = [
  {
    value: "cj",
    label: "从江",
  },
  {
    value: "rj",
    label: "榕江",
  },
  {
    value: "tz",
    label: "天柱",
  },
];

const townList = {
  cj: [
    {
      label: "往洞镇",
      value: "wangdong",
      parentValue: "cj",
    },
    {
      label: "停洞镇",
      value: "tingdong",
      parentValue: "cj",
    },
  ],
  tz: [
    {
      label: "一村",
      value: "yicun",
      parentValue: "tz",
    },
    {
      label: "二村",
      value: "ercun",
      parentValue: "tz",
    },
    {
      label: "三村",
      value: "sancun",
      parentValue: "tz",
    },
  ],
  rj: [
    {
      label: "八吉",
      value: "baji",
      parentValue: "rj",
    },
    {
      label: "古州",
      value: "guzhou",
      parentValue: "rj",
    },
  ],
};

export default function Index() {
  const [tableDataList, setTableDataList] = useState([]); // 左右表格内容

  const [typeTabCheck, setTypeTabCheck] = useState(TabList[0].value); // 分类tab选中

  const [typeItemCheck, setTypeItemCheck] = useState(0); // 栏目tab选中
  const [cloumnModalOpen, setCloumnModalOpen] = useState({
    open: false,
    type: "new",
    data: null,
  }); // 栏目弹窗
  const [cloumnData, setCloumnData] = useState([]); // 栏目数据

  const [materialsModalOpen, setMaterialsModalOpen] = useState({
    open: false,
    type: "new",
    data: null,
  }); // 材料弹窗

  const [uploadFileModalOpen, setUploadFileModalOpen] = useState({
    open: false,
    type: "new",
    data: null,
  }); // 批量上传材料弹窗
  const [uploadFileData, setUploadFileData] = useState([]); // 批量上传材料数据
  const [fileList, setFileList] = useState([]); // 批量上传材料数据

  const [columnsForm] = Form.useForm(); // 栏目弹窗
  const [materialsForm] = Form.useForm(); // 材料弹窗
  // const [fileForm] = Form.useForm(); // 批量上传材料弹窗

  // const headRef = useRef([]);

  useEffect(() => {
    console.log("home:", v4());
    // form.setFieldsValue({
    //   note: "Hi, man!",
    // });
    // form.resetFields();
  }, []);

  const tableColumns = [
    {
      title: "序号",
      dataIndex: "no",
      key: "no",
      // render: (text) => <a>{text}</a>,
      width: 80,
      fixed: "left",
    },
    {
      title: "事项类别",
      dataIndex: "thingsType",
      key: "thingsType",
      fixed: "left",
      width: 100,
      // render: (text) => <a>{text}</a>,
    },
    {
      title: "X的建设类别细分",
      dataIndex: "buildTypeDetails",
      key: "buildTypeDetails",
      width: 100,
      // render: (text) => <a>{text}</a>,
    },
    {
      title: "事项名称",
      dataIndex: "thingsName",
      width: 100,
      key: "thingsName",
    },
    {
      width: 100,
      title: "法律法规及规范性文件",
      dataIndex: "lawFiles",
      key: "lawFiles",
    },
    {
      width: 100,
      title: "电话通知或口头交办",
      dataIndex: "notice",
      key: "notice",
    },
    {
      title: "部门交办",
      dataIndex: "partTodo",
      width: 100,
      key: "partTodo",
    },
    {
      width: 100,
      title: "微信通知",
      dataIndex: "wxMessage",
      key: "wxMessage",
    },
    {
      title: "APP通知",
      width: 100,
      dataIndex: "appMessage",
      key: "appMessage",
    },
    {
      title: "12345工单",
      width: 100,
      dataIndex: "listFile",
      key: "listFile",
    },
    {
      title: "其他",
      width: 100,
      dataIndex: "others",
      key: "others",
    },
    {
      title: "归口业务部门",
      width: 100,
      dataIndex: "classifyPartment",
      key: "classifyPartment",
    },
    {
      width: 100,
      title: "履职主体",
      dataIndex: "dutyBody",
      key: "dutyBody",
    },
    {
      title: "履职程序",
      width: 100,
      dataIndex: "dutyProgrammer",
      key: "dutyProgrammer",
    },
    {
      width: 100,
      title: "正常运行",
      dataIndex: "ing",
      key: "ing",
    },
    {
      width: 100,
      title: "暂停运行",
      dataIndex: "stop",
      key: "stop",
    },
    {
      width: 100,
      title: "基本履职事项",
      dataIndex: "basicThings",
      key: "basicThings",
    },
    {
      title: "配合履职事项",
      dataIndex: "cooperateThings",
      width: 100,
      key: "cooperateThings",
    },
    {
      title: "上级收回事项",
      dataIndex: "backThings",
      width: 100,
      key: "backThings",
    },
    {
      title: "理由",
      dataIndex: "reason",
      width: 100,
      key: "reason",
    },
    {
      width: 100,
      title: "收回事项承接部门",
      dataIndex: "backPart",
      key: "backPart",
    },
    {
      title: "备注",
      dataIndex: "remark",
      width: 100,
      key: "remark",
    },
    {
      width: 100,
      title: "操作",
      key: "action",
      fixed: "right",
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              setMaterialsModalOpen({
                open: true,
                type: "edit",
                data: record,
              });
              materialsForm.setFieldsValue({
                no: record?.no,
                thingsTypeId: record?.thingsTypeId,
                buildTypeDetails: record?.buildTypeDetails,
                thingsName: record?.thingsName,
                lawFiles: record?.lawFiles,
                notice: record?.notice,
                partTodo: record?.partTodo,
                wxMessage: record?.wxMessage,
                appMessage: record?.appMessage,
                listFile: record?.listFile,
                others: record?.others,
                classifyPartment: record?.classifyPartment,
                dutyBody: record?.dutyBody,
                dutyProgrammer: record?.dutyProgrammer,
                ing: record?.ing,
                stop: record?.stop,
                basicThings: record?.basicThings,
                cooperateThings: record?.cooperateThings,
                backThings: record?.backThings,
                reason: record?.reason,
                backPart: record?.backPart,
                remark: record?.remark,
              });
            }}
          >
            编辑
          </a>
          {/* <a>删除</a> */}
        </Space>
      ),
    },
  ];

  // tab选中
  const onTabChange = (key) => {
    setTypeTabCheck(key);
    setTypeItemCheck(0);
  };

  // 导出数据
  const onBtnExportXlsx = () => {
    if (!tableDataList || !tableDataList.length) {
      message.error("暂无数据，请先新增数据");
      return;
    }
    const resultData = [];
    //整合数据
    tableDataList.map((item) => {
      resultData.push([
        item?.no,
        item?.thingsType,
        item?.buildTypeDetails,
        item?.thingsName,
        item?.lawFiles,
        item?.notice,
        item?.partTodo,
        item?.wxMessage,
        item?.appMessage,
        item?.listFile,
        item?.others,
        item?.classifyPartment,
        item?.dutyBody,
        item?.dutyProgrammer,
        item?.ing,
        item?.stop,
        item?.basicThings,
        item?.cooperateThings,
        item?.backThings,
        item?.reason,
        item?.backPart,
        item?.remark,
      ]);
    });
    const head = [
      "序号",
      "事项类别",
      "X的建设类别细分",
      "事项名称",
      "法律法规及规范性文件",
      "电话通知或口头交办",
      "部门交办",
      "微信通知",
      "APP通知",
      "12345工单",
      "其他",
      "归口业务部门",
      "履职主体",
      "履职程序",
      "正常运行",
      "暂停运行",
      "基本履职事项",
      "配合履职事项",
      "上级收回事项",
      "理由",
      "收回事项承接部门",
      "备注",
    ]; // headRef.current 数据中有合并单元格，数据不正常
    resultData.unshift(head);
    console.log("导出数据：", resultData);

    const worksheet = XLSX.utils.json_to_sheet(resultData); //将数据转换为工作表
    const workbook = XLSX.utils.book_new(); //创建一个新的工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1"); //将工作表添加到工作簿
    XLSX.writeFile(workbook, "人员信息.xlsx"); //保存工作簿为文件
  };

  // 新增栏目弹窗
  const onAddColumnsClick = () => {
    setCloumnModalOpen({ type: "new", open: true, data: null });
  };
  const onClunmsModalHandleOk = () => {
    columnsForm.getFieldsValue();
    // console.log("4545:", form.getFieldsValue());
    columnsForm.validateFields().then((value) => {
      console.log("校验通过：", value);
    });
  };

  const onClumnsModalHandleCancel = () => {
    setCloumnModalOpen({ type: "edit", open: false, data: null });
    columnsForm.resetFields();
  };
  // 编辑栏目
  const onEditColumns = (item) => {
    setCloumnModalOpen({ type: "edit", open: true, data: item });
    columnsForm.setFieldsValue({
      columnsType: item?.parentValue,
      columnsName: item?.label,
      columnsId: item?.value,
    });
  };

  //材料弹窗
  const onMaterialsModalHandleOk = () => {
    materialsForm.validateFields().then((value) => {
      console.log("校验通过22：", value);
    });
  };
  const onMaterialsModalHandleCancel = () => {
    setMaterialsModalOpen({
      open: false,
      type: "new",
      data: null,
    });
    materialsForm.resetFields();
  };

  // 批量上传弹窗
  const onUploadModalHandleOk = () => {
    setUploadFileData([]);
    setFileList([]);
    Modal.destroyAll();
    setUploadFileModalOpen({
      open: false,
      type: "new",
      data: null,
    });

    setTableDataList(uploadFileData); // 给页面表格赋值
  };

  const onUploadModalHandleCancel = () => {
    setUploadFileData([]);
    setFileList([]);
    Modal.destroyAll();
    setUploadFileModalOpen({
      open: false,
      type: "new",
      data: null,
    });
  };

  // 批量上传材料
  const beforeUpload = (file) => {
    //创建一个FileReader实例
    const fileReader = new FileReader();
    //读取文件
    fileReader.readAsBinaryString(file);
    //读取完成
    fileReader.onload = () => {
      //读取数据
      const workbook = XLSX.read(fileReader.result, { type: "binary" });
      //获取第一个sheet
      const sheet = workbook.Sheets[workbook.SheetNames[0]];
      //将sheet转成json
      const jsonData = XLSX.utils.sheet_to_json(sheet, { header: 1 }) || [];
      // 表头
      // headRef.current = jsonData?.[1] || [];
      // console.log("head:", headRef.current);
      //数据去除表头
      const fileData = jsonData.filter((item, index) => index > 2);

      const resultData = []; // 将数据，转换成数组对象
      fileData.forEach((item) => {
        const tempThingTypeObj = thingsTypeList.find((ele) => {
          return (
            (item?.[1] &&
              (ele?.label == item?.[1]?.trim?.() ||
                ele?.label2 == item?.[1]?.trim?.())) ||
            ele?.label3 == item?.[1]?.trim?.()
          );
        }) || { label: item?.[1], value: getRandomNumberGreaterThan10000() };
        const tempObj = {
          no: item?.[0],
          thingsType: tempThingTypeObj?.label,
          thingsTypeId: tempThingTypeObj?.value,
          buildTypeDetails: item?.[2],
          thingsName: item?.[3],
          lawFiles: item?.[4],
          notice: item?.[5],
          partTodo: item?.[6],
          wxMessage: item?.[7],
          appMessage: item?.[8],
          listFile: item?.[9],
          others: item?.[10],
          classifyPartment: item?.[11],
          dutyBody: item?.[12],
          dutyProgrammer: item?.[13],
          ing: item?.[14],
          stop: item?.[15],
          basicThings: item?.[16],
          cooperateThings: item?.[17],
          backThings: item?.[18],
          reason: item?.[19],
          backPart: item?.[20],
          remark: item?.[21],
        };
        resultData.push(tempObj);
      });

      // 排序处理
      resultData.sort((a, b) => a?.thingsTypeId - b?.thingsTypeId);
      // 先升序排id，再排name
      // resultData.sort((a, b) => {
      //   if (a.id !== b.id) {
      //     return a.id - b.id;
      //   } else {
      //     return a.name.localeCompare(b.name);
      //   }
      // });

      console.log("resultData", resultData);
      setUploadFileData(resultData);
      setFileList([file]);
    };
  };

  return (
    <div>
      {/** 顶部-筛选条件 */}
      <div className="fliterLine">
        <div>
          <Segmented
            value={typeTabCheck}
            style={{
              marginBottom: 8,
            }}
            onChange={onTabChange}
            options={TabList}
          />
        </div>
        <div>
          <Space>
            <Button
              icon={<UploadOutlined />}
              type="primary"
              onClick={(e) => {
                e.stopPropagation?.();
                setUploadFileModalOpen({
                  open: true,
                  type: "new",
                  data: null,
                });
              }}
            >
              批量上传材料
            </Button>
            <Button
              type="primary"
              icon={<DownloadOutlined style={{ color: "#fff" }} />}
              onClick={onBtnExportXlsx}
            >
              导出
            </Button>
            {/* <Button
              type="primary"
              icon={<PlusOutlined style={{ color: "#fff" }} />}
              onClick={onAddColumnsClick}
            >
              新增栏目
            </Button> */}
          </Space>
        </div>
      </div>

      {/** 内容 */}
      <div className="content">
        {/** 左侧栏目 */}
        {/* <div className="letfContent">
          {townList?.[typeTabCheck] &&
            townList?.[typeTabCheck]?.map((item, i) => {
              return (
                <div
                  key={i}
                  className={`typeItem ${typeItemCheck == i && "typeItemCheck"}`}
                  onClick={() => {
                    setTypeItemCheck(i);
                  }}
                >
                  <div className="valueBox">
                    <div className="name">{item.label}</div>
                    <div>{item?.value}</div>
                  </div>
                  <div className="btnBox">
                    <Space direction="vertical">
                      <Button
                        icon={<PlusOutlined />}
                        onClick={(e) => {
                          e.stopPropagation?.();
                          setMaterialsModalOpen({
                            open: true,
                            type: "new",
                            data: null,
                          });
                        }}
                      >
                        新增材料
                      </Button>
                      <Button
                        icon={<EditOutlined />}
                        onClick={(e) => {
                          e.stopPropagation?.();
                          onEditColumns(item);
                        }}
                      >
                        编辑栏目
                      </Button>
                      <Button icon={<DeleteOutlined />}>删除栏目</Button>
                    </Space>
                  </div>
                </div>
              );
            })}
        </div> */}
        {/** 右侧表格内容 */}
        <div className="rightContent">
          <Table
            columns={tableColumns}
            dataSource={tableDataList}
            scroll={{ x: "80vw" }}
            rowKey="no"
          />
        </div>
      </div>

      {/** 栏目弹窗 */}
      <Modal
        title={cloumnModalOpen.type === "edit" ? "编辑栏目" : "新增栏目"}
        open={cloumnModalOpen.open}
        onOk={onClunmsModalHandleOk}
        onCancel={onClumnsModalHandleCancel}
      >
        <Form
          name="wrap"
          form={columnsForm}
          labelCol={{
            flex: "110px",
          }}
          labelAlign="left"
          labelWrap
          wrapperCol={{
            flex: 1,
          }}
          colon={false}
        >
          <Form.Item
            label="所属分类"
            name="columnsType"
            rules={[{ required: true, message: "请选择所属分类" }]}
          >
            <Select
              placeholder="请选择所属分类"
              options={TabList}
              disabled={cloumnModalOpen.type === "edit"}
            />
          </Form.Item>

          <Form.Item
            label="栏目名称"
            name="columnsName"
            rules={[
              {
                required: true,
                message: "请输入栏目名称",
              },
            ]}
          >
            <Input placeholder="请输入栏目名称" />
          </Form.Item>

          <Form.Item
            label="栏目ID"
            name="columnsId"
            rules={[
              {
                required: true,
                message: "请输入栏目ID",
              },
            ]}
          >
            <Input placeholder="请输入栏目ID" disabled />
          </Form.Item>
        </Form>
      </Modal>

      {/** 材料弹窗 */}
      <Modal
        title={materialsModalOpen.type === "edit" ? "编辑材料" : "新增材料"}
        open={materialsModalOpen.open}
        onOk={onMaterialsModalHandleOk}
        onCancel={onMaterialsModalHandleCancel}
        width={1000}
      >
        <div style={{ maxheight: "700px", overflow: "auto" }}>
          <Form
            name="wrap"
            form={materialsForm}
            labelAlign="left"
            labelWrap
            colon={false}
            labelCol={{
              span: 8,
            }}
            wrapperCol={{
              span: 14,
            }}
          >
            <Row>
              <Col span={12}>
                <Form.Item
                  label="序号"
                  name="no"
                  rules={[
                    {
                      required: true,
                      message: "请输入序号",
                    },
                  ]}
                >
                  <Input placeholder="请输入序号" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="事项类别"
                  name="thingsTypeId"
                  rules={[
                    {
                      required: true,
                      message: "请输入事项类别",
                    },
                  ]}
                >
                  {/* <Input placeholder="请输入事项类别" /> */}
                  <Select
                    placeholder="请选择事项类别"
                    options={thingsTypeList}
                    // disabled={cloumnModalOpen.type === "edit"}
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item label="X的建设类别细分" name="buildTypeDetails">
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="事项名称" name="thingsName">
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item label="法律法规及规范性文件" name="lawFiles">
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="电话通知或口头交办" name="notice">
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item label="部门交办" name="partTodo">
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="微信通知" name="wxMessage">
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item label="APP通知" name="appMessage">
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="12345工单" name="listFile">
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item label="其他" name="others">
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="归口业务部门" name="classifyPartment">
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item label="履职主体" name="dutyBody">
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="履职程序" name="dutyProgrammer">
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item label="正常运行" name="ing">
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="暂停运行" name="stop">
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item label="基本履职事项" name="basicThings">
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="配合履职事项" name="cooperateThings">
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item label="理由" name="reason">
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="收回事项承接部门" name="backPart">
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item label="备注" name="remark">
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}></Col>
            </Row>
          </Form>
        </div>
      </Modal>

      {/** 批量上传材料弹窗 */}
      <Modal
        title="批量上传材料"
        open={uploadFileModalOpen.open}
        onOk={onUploadModalHandleOk}
        onCancel={onUploadModalHandleCancel}
        width={1000}
      >
        <div>
          <Space direction="vertical" style={{ width: "100%" }}>
            <Upload
              fileList={fileList}
              accept=".xlsx,.xls"
              maxCount={1}
              beforeUpload={beforeUpload}
              onRemove={() => {
                setUploadFileData([]);
                setFileList([]);
              }}
            >
              <Button icon={<UploadOutlined />}>选择文件</Button>
            </Upload>
            {/* <Select placeholder="请选择所属分类" options={TabList} /> */}
            {/* <Input placeholder="请输入栏目名称" /> */}
            <div>
              <Table
                columns={tableColumns}
                dataSource={uploadFileData}
                rowKey="no"
                scroll={{ y: "400px" }}
              />
            </div>
          </Space>
        </div>
      </Modal>
    </div>
  );
}
